<template>
  <el-container>
    <order-header title="地址列表">
      <template v-slot:tip>
        <span>请谨防钓鱼链接或诈骗电话，了解更多></span>
      </template>
    </order-header>
    <el-header style="text-align: center; margin: 20px;">
    </el-header>
    <el-main style="margin: 0 300px;">
      <el-table :data="addresses">
        <el-table-column prop="userName" label="收货人"></el-table-column>
        <el-table-column prop="userPhone" label="收货电话"></el-table-column>
        <el-table-column prop="provinceName" label="省份"></el-table-column>
        <el-table-column prop="cityName" label="城市"></el-table-column>
        <el-table-column prop="regionName" label="区县"></el-table-column>
        <el-table-column prop="detailAddress" label="详细地址"></el-table-column>
        <el-table-column label="是否是默认地址">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.defaultFlag === 0">否</el-tag>
            <el-tag v-else>是</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="editAddress(scope.row)">编辑</el-button>
            <el-button size="small" type="text" @click="deleteAddress(scope.row.addressId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="新增地址" :visible.sync="addDialogVisible" @close="clearAddressForm">
        <el-form label-width="150px">
          <el-form-item label="收货人">
            <el-input v-model="addressFormData.userName"></el-input>
          </el-form-item>
          <el-form-item label="收货电话">
            <el-input v-model="addressFormData.userPhone"></el-input>
          </el-form-item>
          <el-form-item label="省市">
            <span v-show="type === 'edit'" style="margin-right: 10px">
              当前省市:{{ addressFormData.provinceName + addressFormData.cityName + addressFormData.regionName }}</span>
            <el-cascader
              size="large"
              :options="pcaTextArr"
              @change="handleRegionChange"
              >
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input v-model="addressFormData.detailAddress"></el-input>
          </el-form-item>
          <el-form-item label="是否设为默认地址">
            <el-switch 
              :value="addressFormData.defaultFlag"
              :active-value="1"
              :inactive-value="0"
              @change="handleDefaultChange">
            </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddressForm">保存</el-button>
        </div>
      </el-dialog>
    </el-main>
    <el-row style="text-align: center; margin: 50px;">
      <el-button type="primary" @click="showAddModal" icon="el-icon-plus">新增地址</el-button>
    </el-row>
    <service-bar></service-bar>
  <nav-footer></nav-footer>
  </el-container>
</template>

<script>
import { getAddressList, addAddress, EditAddress, DeleteAddress } from '../service/address'
import { pcaTextArr  } from 'element-china-area-data'
import ServiceBar from '../components/ServiceBar'
import NavFooter from '../components/NavFooter'
import OrderHeader from '../components/OrderHeader'

export default {
  components:{
    ServiceBar,
    NavFooter,
    OrderHeader
  },
  data() {
    return {
      pcaTextArr ,
      addresses: [],
      addDialogVisible: false,
      addressFormData: {
        userName: '',
        userPhone: '',
        provinceName: '',
        cityName: '',
        regionName: '',
        detailAddress: '',
        defaultFlag: 0
      },
      type: '',
    }
  },
  async mounted() {
    this.init()
  },
  methods: {
    async init() {
      const { data } = await getAddressList()
      this.addresses = data
    },
    showAddModal() {
      this.type = 'add'
      this.addressFormData = {
        userName: '',
        userPhone: '',
        provinceName: '',
        cityName: '',
        regionName: '',
        detailAddress: '',
        defaultFlag: 0
      }
      this.addDialogVisible = true; 
    },
    editAddress(row) {
      this.type = 'edit'
      this.addressFormData = row
      this.addDialogVisible = true
    },
    handleDefaultChange() {
      if(this.addressFormData.defaultFlag === 1) {
        this.addressFormData.defaultFlag = 0
      } else {
        this.addressFormData.defaultFlag = 1
      }
    },
    handleRegionChange(value) {
      this.addressFormData.provinceName = value[0]
      this.addressFormData.cityName = value[1]
      this.addressFormData.regionName = value[2]
    },
    // 删除地址
    async deleteAddress(id) {
      const confirmResult = await this.$confirm('确定要删除该地址吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });

      if (confirmResult === 'confirm') {
        // 调用后端API进行删除操作
        try {
          const response = await DeleteAddress(id);
          if (response.resultCode === 200) {
            // 删除成功后从本地数据中移除对应项
            this.init()
            this.$message({
              message: '地址删除成功',
              type: 'success'
            });
          } else {
            this.$message.error('地址删除失败，请稍后重试');
          }
        } catch (error) {
          this.$message.error('地址删除过程中发生错误');
        }
      }
    },
    // 提交地址表单（添加或更新）
    async submitAddressForm() {
      this.addDialogVisible = false
      if(this.type === 'add') {
        const res = await addAddress(this.addressFormData)
        if(res.resultCode === 200) {
          this.$message.success('新增地址成功')
          this.init()
        }
      } else if(this.type === 'edit') {
        const res = await EditAddress(this.addressFormData)
        if(res.resultCode === 200) {
          this.$message.success('修改成功')
          clearAddressForm()
        }
      }
    },
    // 清空地址表单
    clearAddressForm() {
      this.addressFormData = {
        userName: '',
        userPhone: '',
        provinceName: '',
        cityName: '',
        regionName: '',
        detailAddress: '',
        defaultFlag: 0
      }
    }
  }
}
</script>

<style>

</style>